package com.example.seabedmusic.utils;

import android.content.Context;
import android.content.SharedPreferences;
import com.example.seabedmusic.entity.User;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class UserManager {
    private static final String PREF_NAME = "user_prefs";
    private static final String KEY_CURRENT_USER = "current_user";
    private static final String KEY_IS_LOGGED_IN = "is_logged_in";
    private static final String KEY_REGISTERED_USERS = "registered_users";

    private static UserManager instance;
    private SharedPreferences sharedPreferences;
    private Gson gson;

    private UserManager(Context context) {
        sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        gson = new Gson();
    }

    public static synchronized UserManager getInstance(Context context) {
        if (instance == null) {
            instance = new UserManager(context);
        }
        return instance;
    }

    public void login(User user) {
        String userJson = gson.toJson(user);
        sharedPreferences.edit()
                .putString(KEY_CURRENT_USER, userJson)
                .putBoolean(KEY_IS_LOGGED_IN, true)
                .apply();
    }

    public void logout() {
        sharedPreferences.edit()
                .remove(KEY_CURRENT_USER)
                .putBoolean(KEY_IS_LOGGED_IN, false)
                .apply();
    }

    public boolean isLoggedIn() {
        return sharedPreferences.getBoolean(KEY_IS_LOGGED_IN, false);
    }

    public User getCurrentUser() {
        String userJson = sharedPreferences.getString(KEY_CURRENT_USER, null);
        if (userJson != null) {
            return gson.fromJson(userJson, User.class);
        }
        return null;
    }

    public void updateUserInfo(User user) {
        login(user); // 复用登录方法更新用户信息
    }

    /**
     * 验证用户凭据
     */
    public boolean validateUser(String username, String password) {
        // 预设用户
        if ("111".equals(username) && "111111".equals(password)) {
            return true;
        }

        // 检查是否已注册
        String registeredUsersJson = sharedPreferences.getString(KEY_REGISTERED_USERS, "{}");
        Type type = new TypeToken<Map<String, String>>(){}.getType();
        Map<String, String> registeredUsers = gson.fromJson(registeredUsersJson, type);
        if (registeredUsers == null) {
            registeredUsers = new HashMap<>();
        }

        // 验证用户名和密码是否匹配
        String storedPassword = registeredUsers.get(username);
        return storedPassword != null && storedPassword.equals(password);
    }

    /**
     * 注册新用户
     */
    public boolean registerUser(String username, String password, String email) {
        String registeredUsersJson = sharedPreferences.getString(KEY_REGISTERED_USERS, "{}");
        Type type = new TypeToken<Map<String, String>>(){}.getType();
        Map<String, String> registeredUsers = gson.fromJson(registeredUsersJson, type);
        if (registeredUsers == null) {
            registeredUsers = new HashMap<>();
        }

        // 检查用户是否已存在（排除预设用户）
        if (registeredUsers.containsKey(username) && !"111".equals(username)) {
            return false; // 用户已存在
        }

        // 添加新用户
        registeredUsers.put(username, password);
        sharedPreferences.edit()
                .putString(KEY_REGISTERED_USERS, gson.toJson(registeredUsers))
                .apply();
        return true;
    }

    /**
     * 检查用户名是否已存在
     */
    public boolean isUsernameExists(String username) {
        // 预设用户名不能注册
        if ("111".equals(username)) {
            return true;
        }

        String registeredUsersJson = sharedPreferences.getString(KEY_REGISTERED_USERS, "{}");
        Type type = new TypeToken<Map<String, String>>(){}.getType();
        Map<String, String> registeredUsers = gson.fromJson(registeredUsersJson, type);
        if (registeredUsers == null) {
            return false;
        }

        return registeredUsers.containsKey(username);
    }
}